/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.model;

import br.com.jr2tecnologia.model.entity.BankAccount;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.entity.Credit;
import br.com.jr2tecnologia.model.persistence.DAOFactory;
import br.com.jr2tecnologia.model.repository.BankAccountRepository;
import br.com.jr2tecnologia.model.repository.CreditRepository;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author ronildo
 */
@Stateless
public class CreditPersistence implements CreditPersistenceLocal {
    
    @PersistenceContext
    private EntityManager em;
    private BankAccountRepository bankAccountRepository;
    private CreditRepository creditRepository;
    
    @PostConstruct
    public void initialize(){
        creditRepository = DAOFactory.getCreditRepository(em);
        bankAccountRepository = DAOFactory.getBankAccountRepository(em);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void persist(Credit credit) {
        BankAccount bankAccount = bankAccountRepository.findById(credit.getBankAccount());
        Company company = bankAccount.getCompany();

        long qtdSmsBuyed = Math.round(credit.getValue() / company.getValueSendSms());
        bankAccount.setQuantitySmsBuyed( bankAccount.getQuantitySmsBuyed() + qtdSmsBuyed);
        bankAccount.setBalance( bankAccount.getBalance() + credit.getValue() );

        creditRepository.persist(credit);
        bankAccountRepository.update(bankAccount);
    }

    public void update(Credit entity) {
        creditRepository.update(entity);
    }

    public void remove(Credit entity) {
        creditRepository.remove(entity, entity.getPkCredit());
    }

    public Credit findById(Long id) {
        return creditRepository.findById(id);
    }

    public Credit findByValue(Double value) {
        return creditRepository.findByValue(value);
    }

    public List<Credit> list(Credit credit){
        return creditRepository.list(credit);
    }

    public List<Credit> listAll(){
        return creditRepository.listAll();
    }
}
